import os
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QPushButton, QLabel, QHBoxLayout, \
    QScrollArea, QFrame, QSizePolicy, QSpacerItem
from PyQt5.QtGui import QFont, QPixmap, QColor, QPolygon, QPainter, QIcon
from PyQt5.QtCore import Qt, QRect, QSize, pyqtSignal, QThread
from bubble_message import BubbleMessage
from shangxiawen import get_access_token, Chat

c = Chat(get_access_token())
# base_path = os.path.dirname(os.path.abspath(__file__))


class MessageType:
    Text = 1
    Image = 2


class ChatBubble(QFrame):
    def __init__(self, text, is_user=True):
        super().__init__()
        self.text = text
        self.is_user = is_user
        self.initUI()

    def initUI(self):
        # 创建头像标签
        self.avatar_label = QLabel()
        if self.is_user:
            self.avatar_label.setPixmap(
                QIcon(os.path.join(base_path, "resources", "user_avatar.png")).scaled(40, 40, Qt.KeepAspectRatio))
        else:
            self.avatar_label.setPixmap(
                QIcon(os.path.join(base_path, "resources", "chatgpt_avatar.png")).scaled(40, 40, Qt.KeepAspectRatio))

        self.label = QLabel(self.text)
        self.label.setFont(QFont('Arial', 12))
        self.label.setWordWrap(True)  # 允许换行
        self.label.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        self.label.setTextInteractionFlags(Qt.TextSelectableByMouse)  # 允许选中文本

        # 设置背景颜色和边框弧度
        if self.is_user:
            self.label.setStyleSheet('background-color: #DCF8C6; padding: 10px; border-radius: 10px;')
        else:
            self.label.setStyleSheet('background-color: #FFFFFF; padding: 10px; border-radius: 10px;')

        # 设置最大宽度，避免气泡过宽
        self.label.setMaximumWidth(800)  # 设置最大宽度为400像素

        # 设置自适应大小策略
        self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # 创建内部布局
        inner_layout = QHBoxLayout()
        inner_layout.addWidget(self.label)
        inner_layout.setContentsMargins(0, 0, 0, 0)
        inner_layout.setSpacing(0)

        # 创建外部布局
        outer_layout = QHBoxLayout()
        if self.is_user:
            outer_layout.addStretch(1)  # 推动气泡靠右对齐
            outer_layout.addLayout(inner_layout)
            outer_layout.addSpacing(10)  # 添加一些间距
            outer_layout.addWidget(self.avatar_label)

        else:
            outer_layout.addWidget(self.avatar_label)
            outer_layout.addSpacing(10)  # 添加一些间距
            outer_layout.addLayout(inner_layout)
            outer_layout.addStretch(1)  # 推动气泡靠左对齐
        self.setLayout(outer_layout)

        # self.setStyleSheet('background-color: transparent; border: none;')
        self.setFrameShape(QFrame.NoFrame)

        # 调整气泡大小以适应内容
        self.adjustSize()

    def adjustSize(self):
        # 计算文本的宽度和高度
        text_width = self.label.fontMetrics().width(self.text)
        text_height = self.label.fontMetrics().height() * (self.text.count('\n') + 1)
        bubble_width = min(max(text_width + 20, 200), 800)  # 最小宽度为200，最大宽度为400
        # bubble_width = min(text_width + 20, 800)  # 最小宽度为200，最大宽度为400
        bubble_height = text_height + 10  # 上下各10px的padding

        self.label.setFixedWidth(bubble_width)
        self.setFixedWidth(bubble_width + 60)  # 加上头像的宽度和间距
        self.label.adjustSize()  # 调整标签高度以适应内容
        self.setFixedHeight(self.label.height() + 20)  # 上下各10px的padding

        # 确保气泡的四个角都有弧度
        self.setStyleSheet(f'background-color: {"#DCF8C6" if self.is_user else "#FFFFFF"}; border-radius: 10px;')


class ChatWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('智能问答聊天框')
        self.setWindowIcon(QIcon(os.path.join(base_path, "resources", "小小机器人.png")))
        self.setGeometry(100, 100, 1000, 800)  # 设置初始窗口大小为 1000x800

        # 创建滚动区域
        self.scroll_area = QScrollArea()
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setStyleSheet('background-color: #F0F0F0; border: none;')

        # 创建聊天内容容器
        self.chat_container = QWidget()
        self.chat_layout = QVBoxLayout()
        self.chat_layout.setAlignment(Qt.AlignBottom)
        self.chat_container.setLayout(self.chat_layout)
        self.scroll_area.setWidget(self.chat_container)

        # 创建输入框
        self.text_edit = QTextEdit()
        self.text_edit.setPlaceholderText('请输入问题...')
        self.text_edit.setFont(QFont('Arial', 12))
        self.text_edit.setStyleSheet(
            'background-color: #FFFFFF; border: 1px solid #CCCCCC; border-radius: 5px; padding: 5px;')
        self.text_edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # 创建发送按钮
        self.send_button = QPushButton('发送')
        self.send_button.setFont(QFont('Arial', 12))
        self.send_button.setStyleSheet(
            'background-color: #1E90FF; color: #FFFFFF; border: none; border-radius: 5px; padding: 5px;')
        self.send_button.clicked.connect(self.send_message)

        # 创建底部布局
        bottom_layout = QHBoxLayout()
        bottom_layout.addWidget(self.text_edit)
        bottom_layout.addWidget(self.send_button)

        # 创建主布局
        main_layout = QVBoxLayout()
        main_layout.addWidget(self.scroll_area)
        main_layout.addLayout(bottom_layout)

        self.setLayout(main_layout)

        # 设置布局权重
        main_layout.setStretchFactor(self.scroll_area, 1)
        main_layout.setStretchFactor(bottom_layout, 0)

    def send_message(self):
        question = self.text_edit.toPlainText()
        if question:
            self.add_chat_bubble(question, True)
            # 这里可以调用接入 ChatGPT 的函数获取回答
            # 例如：answer = get_chatgpt_answer(question)
            answer = c.ask(question)
            # 模拟回答
            # answer = 'ChatGPT：这是模拟的回答内容，可以是多行文。'
            self.add_chat_bubble(answer, False)
            self.text_edit.clear()

    def add_chat_bubble(self, text, is_user):
        # bubble = ChatBubble(text, is_user)
        bubble = BubbleMessage(str_content=text, avatar='', Type=1, is_send=is_user, )
        self.chat_layout.addWidget(bubble)
        # self.chat_layout.setAlignment(bubble, Qt.AlignRight if is_user else Qt.AlignLeft)
        # self.scroll_area.verticalScrollBar().setValue(self.scroll_area.verticalScrollBar().maximum())


def main():
    app = QApplication(sys.argv)
    chat_window = ChatWindow()
    chat_window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    if getattr(sys, 'frozen', False):
        base_path = sys._MEIPASS  # 打包后的临时资源目录
    else:
        base_path = os.path.dirname(__file__)  # 开发环境目录
    main()
